package com.iqiyi.pps.epg.core.async;

import com.iqiyi.kiwi.utils.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by karkarrotxu on 2015/12/3.
 */
public class AsyncService {
    private static final long SLEEP_TIME = 2000l;
    private final BlockingQueue<IAsyncTask> tasks = new ArrayBlockingQueue<IAsyncTask>(
            1000);
    protected boolean enable = queryEnable();
    private final Thread service = initService();
    private static final Logger logger = LoggerFactory.getLogger(AsyncService.class);

    public AsyncService() {
        if (service != null) {
            this.service.start();
            this.service.setName(this.getClass().getSimpleName());
        }
    }

    protected boolean queryEnable() {
        return getEnable(null);
    }

    protected boolean getEnable(String queryName) {
        String controlValue = null;
        if (queryName != null) {
            controlValue = Configuration.getString("async.control." + queryName);
        }
        if (controlValue == null) {
            controlValue = Configuration.getString("async.control.default");
        }
        return Boolean.valueOf(controlValue);
    }

    public static boolean isProductionEnv() {
        return "production".equals(Configuration.getString("deploy.env"));
    }

    protected void accept(IAsyncTask task) {
        if(!this.enable){
            return ;
        }
        try {
            tasks.put(task);
        } catch (NullPointerException npe) {
            logger.error("npe = {}", npe);
        } catch (InterruptedException e) {
            logger.error("InterruptedException = {}", e);
        } catch (Exception e) {
            logger.error("Exception = {}", e);
        }
    }

    /**
     * @return thread
     */
    private Thread initService() {
        logger.info(" enable {}  {}", enable , this.getClass().getName());
        if (!this.enable) {
            return null;
        }
        return new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    logger.error("InterruptedException = {}", e);
                }
                while (true) {
                    try {
                        tasks.take().doTask();
                    } catch (Exception e) {
                        logger.error("Exception = {}", e);
                    }
                }

            }

        });
    }

    protected Thread getThread() {
        return this.service;
    }
}
